/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
* RDBConnectionView.java
*
* Created on December 15, 2007, 12:17 PM
 */
package db.gui;

import db.genomemap.RDBSettings;

import javautil.swing.SwingUtil;
import javautil.swing.components.ProgressSupport;
import javautil.swing.components.ProgressSupportable;

/**
 *
 * @author  stewari1
 */
public class RDBConnectionView extends javax.swing.JPanel implements ProgressSupportable {

    /** Field description */
    private boolean connectionPassed = false;

    /** Field description */
    private RDBConnectionModel model = null;

    /** Field description */
    private ProgressSupport progressSupport = null;


    // Variables declaration - do not modify//GEN-BEGIN:variables

    /** Field description */
    private javax.swing.JPanel connection_JPanel;

    /** Field description */
    private javax.swing.JCheckBox defaultModel_JCheckBox;

    /** Field description */
    private javax.swing.JComboBox jComboBox1;

    /** Field description */
    private javax.swing.JLabel jLabel1;

    /** Field description */
    private javax.swing.JLabel jLabel2;

    /** Field description */
    private javax.swing.JLabel jLabel3;

    /** Field description */
    private javax.swing.JLabel jLabel4;

    /** Field description */
    private javax.swing.JLabel jLabel5;

    /** Field description */
    private javax.swing.JLabel jLabel6;

    /** Field description */
    private javax.swing.JLabel jLabel7;

    /** Field description */
    private javax.swing.JButton lookUpSchemas_JButton;

    /** Field description */
    private javax.swing.JPasswordField passwordField;

    /** Field description */
    private javax.swing.JTextField port_JTextField;

    /** Field description */
    private javax.swing.JTextField schema_JTextField;

    /** Field description */
    private javax.swing.JTextField serverHost_JTextField;

    /** Field description */
    private javax.swing.JComboBox serverType_JComboBox;

    /** Field description */
    private javax.swing.JButton storedConns_JButton;

    /** Field description */
    private javax.swing.JButton testConn_JButton;

    /** Field description */
    private javax.swing.JTextField userName_JTextField;


    // End of variables declaration//GEN-END:variables

    /** Creates new form RDBConnectionView */
    public RDBConnectionView() {

        initComponents();

        progressSupport = new ProgressSupport(this);
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */


    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

        connection_JPanel      = new javax.swing.JPanel();
        jLabel1                = new javax.swing.JLabel();
        jComboBox1             = new javax.swing.JComboBox();
        storedConns_JButton    = new javax.swing.JButton();
        jLabel2                = new javax.swing.JLabel();
        jLabel3                = new javax.swing.JLabel();
        jLabel4                = new javax.swing.JLabel();
        jLabel5                = new javax.swing.JLabel();
        jLabel6                = new javax.swing.JLabel();
        serverHost_JTextField  = new javax.swing.JTextField();
        userName_JTextField    = new javax.swing.JTextField();
        schema_JTextField      = new javax.swing.JTextField();
        port_JTextField        = new javax.swing.JTextField();
        lookUpSchemas_JButton  = new javax.swing.JButton();
        defaultModel_JCheckBox = new javax.swing.JCheckBox();
        testConn_JButton       = new javax.swing.JButton();
        passwordField          = new javax.swing.JPasswordField();
        serverType_JComboBox   = new javax.swing.JComboBox();
        jLabel7                = new javax.swing.JLabel();

        connection_JPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        connection_JPanel.setBorder(
            javax.swing.BorderFactory.createTitledBorder("Connect to MySQL Server Instance"));
        jLabel1.setText("Stored Connection");
        connection_JPanel.add(jLabel1,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, -1));
        connection_JPanel.add(jComboBox1,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, 310, -1));
        storedConns_JButton.setText("...");
        connection_JPanel.add(storedConns_JButton,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 60, 30, -1));
        jLabel2.setText("Server Host");
        connection_JPanel.add(jLabel2,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 90, -1, -1));
        jLabel3.setText("Port");
        connection_JPanel.add(jLabel3,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 90, -1, -1));
        jLabel4.setText("Username");
        connection_JPanel.add(jLabel4,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 120, -1, -1));
        jLabel5.setText("Password");
        connection_JPanel.add(jLabel5,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 150, -1, -1));
        jLabel6.setText("Schema");
        connection_JPanel.add(jLabel6,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 190, -1, -1));
        connection_JPanel.add(serverHost_JTextField,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 90, 190, -1));
        connection_JPanel.add(userName_JTextField,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 120, 190, -1));
        schema_JTextField.setToolTipText("Optional for testing connection");
        connection_JPanel.add(schema_JTextField,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 190, 190, -1));
        connection_JPanel.add(port_JTextField,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 90, 50, -1));
        lookUpSchemas_JButton.setText("Look Up");
        connection_JPanel.add(lookUpSchemas_JButton,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 190, -1, -1));
        defaultModel_JCheckBox.setSelected(true);
        defaultModel_JCheckBox.setText("Select as My Default RDB Connection");
        defaultModel_JCheckBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
        defaultModel_JCheckBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
        connection_JPanel.add(defaultModel_JCheckBox,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 240, -1, -1));
        testConn_JButton.setText("Test Connection");
        testConn_JButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                testConn_JButtonActionPerformed(evt);
            }

        });
        connection_JPanel.add(testConn_JButton,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 230, -1, -1));
        connection_JPanel.add(passwordField,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 150, 190, -1));
        serverType_JComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
            "MySQL" }));
        serverType_JComboBox.addItem(RDBSettings.SERVER_TYPE_MSSQL);
        serverType_JComboBox.addItem(RDBSettings.SERVER_TYPE_ORACLE);
        serverType_JComboBox.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serverType_JComboBoxActionPerformed(evt);
            }

        });
        connection_JPanel.add(serverType_JComboBox,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 30, 70, -1));
        jLabel7.setText("<html>\n<b>Server Type</b>\n</html>");
        connection_JPanel.add(jLabel7,
                              new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 30, -1, -1));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);

        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                connection_JPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 500,
                javax.swing.GroupLayout.PREFERRED_SIZE));
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
                connection_JPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE));

    }    // </editor-fold>//GEN-END:initComponents

    public ProgressSupport getProgressSupport() {
        return progressSupport;
    }

    public void setVisibleDefaultModelCheckBox(boolean show) {
        defaultModel_JCheckBox.setVisible(show);
    }

    public void setTextDefaultModelCheckBox(String txt, boolean selected) {

        defaultModel_JCheckBox.setText(txt);
        defaultModel_JCheckBox.setSelected(selected);
    }

    /**
     * Method description
     *
     * @param evt description
     */
    private void serverType_JComboBoxActionPerformed(java.awt.event.ActionEvent evt) {    // GEN-FIRST:event_serverType_JComboBoxActionPerformed


        // update the title of the connection panel
        connection_JPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Connect to "
                + serverType_JComboBox.getSelectedItem() + " Server Instance"));
    }    // GEN-LAST:event_serverType_JComboBoxActionPerformed

    /**
     * Note: setting a <CODE>null</CODE> model would have the effect of
     * clearing the data as the null model has empty strings for all of its
     * fields.
     */
    public void setModel(RDBConnectionModel model) {

        this.model = model;


        // fill up the fields with the model data.
        serverHost_JTextField.setText(model.getServerHost());
        port_JTextField.setText(model.getPort());
        userName_JTextField.setText(model.getUserName());
        passwordField.setText(model.getPassword());
        schema_JTextField.setText(model.getSchema());
    }

    public RDBConnectionModel getModel() {


        // make sure model is set properly
        if (!isConnectionPassed()) {

            testConnection();

            if (!isConnectionPassed()) return null;
        }


        // get the schema. connection passed -> model has been instantiated
        if (model.getSchema().length() == 0) {

            progressSupport.setHtmlStatusInfo("<b>Schema field is Empty !</b>");

            return null;
        }

        return model;
    }

    /**
     * Method description
     *
     * @param evt description
     */
    private void testConn_JButtonActionPerformed(java.awt.event.ActionEvent evt) {    // GEN-FIRST:event_testConn_JButtonActionPerformed
        testConnection();
    }    // GEN-LAST:event_testConn_JButtonActionPerformed

    boolean testConnection() {

        String errStr = getErrString();

        if (errStr != null) {

            SwingUtil.showErrorDialog(this, errStr);

            return false;
        }

        model = new RDBConnectionModel();

        model.setServerType((String) serverType_JComboBox.getSelectedItem());
        model.setServerHost(serverHost_JTextField.getText());
        model.setUserName(userName_JTextField.getText());
        model.setPassword(new String(passwordField.getPassword()));

        if (schema_JTextField.getText().length() > 0) model.setSchema(schema_JTextField.getText());

        RDBConnection rdbConnection = new RDBConnection();

        rdbConnection.setConnectionModel(model);

        this.connectionPassed = rdbConnection.connect();


        // reporting.
        String testStr = "";

        if (connectionPassed) {
            testStr += "<b>Connection Succeeded ! </b>";
        } else {
            testStr += "<b>Connection Failed !</b>";
        }

        progressSupport.setHtmlStatusInfo(testStr);

        return connectionPassed;
    }

    /**
     * does a primary checking of the necessary fields before the data is
     * processed. A suitable error string is sent to show warning. For
     * no error a null is sent.
     *
     * @return description
     */
    private String getErrString() {

        String errStr = "";

        if (serverHost_JTextField.getText().length() == 0) errStr += "Server Host field is Empty !";
        if (port_JTextField.getText().length() == 0) errStr += "Port field is Empty !";
        if (userName_JTextField.getText().length() == 0) errStr += "Username field is Empty !";
        if (passwordField.getPassword().length == 0) errStr += "Password field is Empty !";
        if (errStr.equals("")) return null;
        else return errStr;
    }

    boolean isConnectionPassed() {
        return connectionPassed;
    }

    public void setConnectionPassed(boolean connectionPassed) {
        this.connectionPassed = connectionPassed;
    }

    public boolean isConnectionDefault() {
        return defaultModel_JCheckBox.isSelected();
    }
}
